﻿using System;
using System.Net;

namespace IOP.Extension.Convert
{
    /// <summary>
    /// IP地址转换扩展
    /// </summary>
    public static class IPAddressConvertExtension
    {
        /// <summary>
        /// 将字符串转化为IP地址
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public static IPEndPoint ToIpAddress(this string code)
        {
            string[] array = code.Split(':');
            IPAddress address = null;
            int port = 0;
            if (array.Length < 2) throw new FormatException("IPAddress convert failed");
            if(array.Length > 2)
            {
                string[] ipv6 = new string[array.Length - 1];
                Array.Copy(array, 0, ipv6, 0, array.Length - 1);
                address = IPAddress.Parse(string.Join(":", ipv6));
                port = int.Parse(array[array.Length - 1]);
                return new IPEndPoint(address, port);
            }
            else
            {
                address = IPAddress.Parse(array[0]);
                port = int.Parse(array[1]);
                return new IPEndPoint(address, port);
            }
        }
    }
}
